<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\model;

use buwang\base\BaseModel;
use buwang\traits\JwtTrait;
use app\common\model\MiniappModule;
use app\common\model\Miniapp;

/**角色权限节点中间表
 * Class AuthNode
 * @package app\manage\model
 */
class AuthGroupNode extends BaseModel
{
    protected $pk = 'id';
    // 表名
    protected $table = 'bw_auth_group_node';
    protected $updateTime = '';

    protected $deleteTime = '';


    //得到列表
    public static function getlist($where = [])
    {
        $topAdminRoleId = config('auth.super_admin_role_id');//超级管理员角色
        //得到所有角色
        $groups = AuthGroup::valiWhere()->where($where)->order('sort desc, id desc')->select()->toArray();


        //返回数据
        $res = array();
        foreach ($groups as $group) {
            $data = array();
            $data['is_super_role'] = false;
            if($topAdminRoleId == $group['id']) $data['is_super_role'] = true;
            $data['id'] = $group['id'];
            $data['pid'] = $group['pid'];
            $data['sort'] = $group['sort'];
            $data['name'] = $group['name'];
            $data['group_name'] = $group['group_name'];
            $data['status'] = $group['status'];
            $data['rules'] = null;
            //查询所有权限，以逗号拼接
            $rules = self::valiWhere()->where('group_id', $group['id'])->column('node_id');
            if ($rules) $data['rules'] = implode(",", $rules);
            $res[] = $data;
        }
        return $res;
    }

    //得到列表
    public static function getMemberlist($where = [],$member_id,$have_system = false)
    {
        //返回数据
        $res = array();
         //得到自定义角色
        $customGroupIds = AuthGroup::valiWhere()->where($where)->column('id');
        if($have_system){
            //得到拥有的系统角色
            //查询中间表得到拥有的全部角色
            $SystemGroupIds = AuthGroupAccess::valiWhere()->where('uid',$member_id)->where('scopes','member')->column('group_id');
            //过滤得到系统角色 （可注释）
            if($SystemGroupIds)$SystemGroupIds= AuthGroup::valiWhere()->where('id','in',$SystemGroupIds)->where('status',1)->where('member_id',0)->where('scopes','member')->column('id');
            //得到自定义角色和拥有角色的并集
            $groupids = array_merge($SystemGroupIds,$customGroupIds);//合并两个数组
            $groups= AuthGroup::valiWhere()->where('id','in',$groupids)->order('sort desc, id desc')->select()->toArray();
        }else{
            $groups= AuthGroup::valiWhere()->where('id','in',$customGroupIds)->order('sort desc, id desc')->select()->toArray();
        }



        foreach ($groups as $group) {
            $data = array();
            $data['id'] = $group['id'];
            $data['pid'] = $group['pid'];
            $data['sort'] = $group['sort'];
            $data['name'] = $group['name'];
            $data['scopes'] = $group['scopes'];
            $data['member_id'] = $group['member_id'];
            $data['group_name'] = $group['group_name'];
            $data['status'] = $group['status'];
            $data['rules'] = null;
            //查询所有权限，以逗号拼接
            $rules = self::valiWhere()->where('group_id', $group['id'])->column('node_id');
            if ($rules) $data['rules'] = implode(",", $rules);
            $res[] = $data;
        }
        return $res;
    }



    //得到一条数据
    public static function getFind($id)
    {
        //得到所有角色
        $group = AuthGroup::valiWhere()->find($id);
        //返回数据
        $res = array();
        if ($group) {
            $res = array();
            $res['id'] = $group['id'];
            $res['pid'] = $group['pid'];
            $res['sort'] = $group['sort'];
            $res['name'] = $group['name'];
            $res['status'] = $group['status'];
            $res['rules'] = null;
            //查询所有权限，以逗号拼接
            $rules = self::valiWhere()->where('group_id', $group['id'])->column('node_id');
            if ($rules) $res['rules'] = implode(",", $rules);

        }
        return $res;
    }


    /*
* 设置查询初始化条件
* @param string $alias 表别名
* @param object $model 模型实例化对象
* @return object
* */
    public static function valiWhere($alias = '', $model = null)
    {
        $model = is_null($model) ? new self() : $model;
        if ($alias) {
            $model = $model->alias($alias);
            $alias .= '.';
        }
        // return  $model->where("{$alias}delete_time", 0);
        return $model;
    }


    /**更新权限
     * @param $id
     * @param $rules
     */
    public static function updateRule($id, $rules, $trans = false)
    {
        if(!$rules) return self::setError('节点不存在');
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = true;
        try {
            //删除之前的权限
            $res1 = self::destroy(function ($query) use ($id) {
                $query->where('group_id', '=', $id);
            });
            $all = array();

            $rules = array_unique($rules);
            //添加新的权限节点
            foreach ($rules as $rule) {
                //得到节点信息
                $node = AuthNode::find($rule);
                if (!$node) return self::setError('节点不存在');
                $data = [
                    'group_id' => $id,
                    'node_id' => $rule,
                    'node_name' => $node['name'],
                    'auth_name' => $node['auth_name'],
                    'type' => $node['type'],
                ];
                $all[] = $data;
            }

            //var_dump($all);die;
           
            if ($rules) {
                $self = new self;
                $res2 = $self->saveAll($all);
            }


            $res = $res && $res1 && $res2 && true;
            if ($trans) {
                self::checkTrans($res);
            }
            if (!$res1) return self::setError('删除节点失败');
            if (!$res2) return self::setError('插入节点失败');
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            return self::setError($e->getMessage());
        }
        if (!$res) return self::setError('更新节点失败');

        return $res;

    }



    //得到列表
    public static function getMeberlist($where = [],$miniapp_id=0)
    {
        $topAdminRoleId = config('auth.super_admin_role_id');//超级管理员角色
        if(!$miniapp_id){

            //得到所有角色
            $groups = AuthGroup::valiWhere()->where($where)->order('sort desc, id desc')->select()->toArray();
        }else{
            if($miniapp_id==-1){
                //查询非应用基础的角色
                $group_ids = MiniappModule::column('group_id');
                $groups = AuthGroup::valiWhere()->where($where)->where('id','not in',$group_ids)->order('sort desc, id desc')->select()->toArray();

            }else{
                //查询应用下的角色
                $group_ids = MiniappModule::where('miniapp_id',$miniapp_id)->column('group_id');
                $groups = AuthGroup::valiWhere()->where($where)->where('id','in',$group_ids)->order('sort desc, id desc')->select()->toArray();
            }

        }


        $miniapp_ids = array();
        //返回数据
        $res = array();
        foreach ($groups as $group) {
            $data = array();
            $data['is_super_role'] = false;
            $data['is_miniapp'] = false;
            if($topAdminRoleId == $group['id']) $data['is_super_role'] = true;
            //查询是否是应用角色如果是应用角色，父id默认为应用id
            $MiniappModule = MiniappModule::where('group_id',$group['id'])->find();
            if($MiniappModule){
                $data['pid'] = $MiniappModule['miniapp_id'];
                $miniapp_ids[] = $MiniappModule['miniapp_id'];
            }else{
                $data['pid'] = $group['pid'];
            }
            $data['id'] = $group['id'];
            $data['sort'] = $group['sort'];
            $data['name'] = $group['name'];
            $data['group_name'] = $group['group_name'];
            $data['status'] = $group['status'];
            $data['rules'] = null;
            //查询所有权限，以逗号拼接
            $rules = self::valiWhere()->where('group_id', $group['id'])->column('node_id');
            if ($rules) $data['rules'] = implode(",", $rules);
            $res[] = $data;
        }
        if($miniapp_ids){
            //根据应用ID查询有效的应用数据
            $miniapps =  Miniapp::where('id','in',$miniapp_ids)->select()->toArray();
            //为应用组装父节点
            foreach ($miniapps as $miniapp) {
                $data = array();
                $data['is_super_role'] = false;
                $data['is_miniapp'] = true;
                $data['pid'] = 0;
                $data['id'] = $miniapp['id'];
                $data['sort'] = 999;
                $data['name'] = $miniapp['title'];
                $data['group_name'] = $miniapp['dir'];
                $data['status'] = 1;
                $data['rules'] = null;
                $res[] = $data;
            }
        }


        return $res;
    }


}
